package javacourse.mq.mymq.Controller;

import javacourse.mq.mymq.service.QueueOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * Create by chenhd on 2021/11/6.
 */
@RestController
@RequestMapping("/api/mqClient")
public class ConsumerController {
    @Autowired
    QueueOperator queueOperator;

    /**
     * 消费消息，支持阻塞、超时
     *
     * @param topic
     * @param consumer
     * @param timeout
     * @return
     */
    @RequestMapping("/consume")
    public Map<String, Object> consumeMessage(String topic, String consumer, Integer timeout) {
        return queueOperator.consume(topic, consumer, timeout);
    }

    /**
     * 提交位移
     *
     * @param topic
     * @param consumer
     * @param offset
     * @return
     */
    @RequestMapping("/consumerConfirm")
    public Boolean consumerConfirm(String topic, String consumer, Integer offset) {
        return queueOperator.commitOffset(topic, consumer, offset);
    }

    /**
     * 为consumer分配partition
     *
     * @param assignRequestEntity
     * @return
     */
    @RequestMapping(value = "/assign", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public Boolean assignConsumer(@RequestBody AssignRequestEntity assignRequestEntity) {
        return queueOperator.assignConsumer(assignRequestEntity.getTopic(), assignRequestEntity.getConsumers());
    }
}
